import React, {Component} from "react";
import {PageHeaderWrapper} from "@ant-design/pro-layout";
import {Card, DatePicker, Table, Typography, Button} from "antd";
import time, {dateFormat, getMockTime} from "@/utils/time"
import {connect} from "dva";
import moment from "moment";
import {AgGridReact} from 'ag-grid-react';
import 'ag-grid-community/dist/styles/ag-grid.css';
import 'ag-grid-community/dist/styles/ag-theme-material.css';
import {overlayLoadingTemplate, overlayNoRowsTemplate} from "@/config/appConfig";


const {RangePicker} = DatePicker;


class History extends Component {

  state = {
    startTime: time.getStartOfDay(),
    endTime: new Date(time.getStartOfDay().valueOf() + 60 * 24 * 60 * 1000),
    gridApi: null,
    gridColumnApi: null,
    defaultColDef: {
      resizable: true
    },
    zao: null
  };


  async componentDidMount() {
    const payload  = await getMockTime("GaoLu")
    this.setState({
      startTime: payload.start,
      endTime: new Date(payload.start.valueOf() + 60 * 24 * 60 * 1000),
    })


    const o = document.body;
    let mainHeight = o.clientHeight || o.offsetHeight;
    this.setState({mainHeight});
    this.fetch()
  }

  timePick = (value) => {
    this.state.startTime = value[0].toDate();
    this.state.endTime = value[1].toDate();
    this.fetch()
  };


  onGridReady = params => {
    this.state.gridApi = params.api;
    this.state.gridColumnApi = params.columnApi;
  };

  fetch = () => {
    const {startTime, endTime} = this.state;
    const payload = {
      start: dateFormat(startTime),
      end: dateFormat(endTime)
    };

    this.props.dispatch({
      type: 'gaolu/getHistory',
      payload
    });

  };


  downloadHistory = () => {
    const {startTime, endTime} = this.state;

    const payload = {
      start: dateFormat(startTime),
      end: dateFormat(endTime)
    };
    const fileName = `${dateFormat(startTime)  }至${  dateFormat(endTime)  }数据.xlsx`;
    this.props.dispatch({
      type: 'gaolu/downloadHistory',
      payload,
      callback: blob => {
        // 回调触发文件下载
        if (window.navigator.msSaveOrOpenBlob) {
          navigator.msSaveBlob(blob, fileName);
        } else {
          const link = document.createElement('a');
          const evt = document.createEvent('MouseEvents');
          link.style.display = 'none';
          link.href = window.URL.createObjectURL(blob);
          link.download = fileName;
          document.body.appendChild(link); // 此写法兼容可火狐浏览器
          evt.initEvent('click', false, false);
          link.dispatchEvent(evt);
          document.body.removeChild(link);
        }
      }
    });
  };

  static getDerivedStateFromProps(nextProps, prevState) {
    const {gridApi, fetchingHistoryNotice} = prevState;
    const {predictHistory} = nextProps;

    let spanBlock;
    if (predictHistory) {
      spanBlock = {}
      let banbie = null;
      let currentBlock = null;
      predictHistory.forEach((item, index) => {
        if (item.banbie !== banbie) {
          banbie = item.banbie;
          currentBlock = {index, value: banbie,height:1};
          spanBlock[index] = currentBlock
        } else {
          currentBlock.height +=1
        }
      });
    }

    if (gridApi && fetchingHistoryNotice) {
      gridApi.showLoadingOverlay()
    }
    return {spanBlock}

  }

  render() {

    const {predictHistory} = this.props;
    const {startTime, endTime,mainHeight} = this.state;
    const columns = [
      {
        headerName: '班别',
        field: 'banbie',
        width: 120,
        rowSpan: params => {
          const {spanBlock} = this.state
          const index = params.node.childIndex;
          if (spanBlock && spanBlock[index]){
            return spanBlock[index].height
          }
          return 1;
        },
        cellClassRules: {
          'cell-span': "value==='早班' || value==='Ryan Lochte'",
        },

      },
      {
        headerName: "班次",
        field: "banci",
        width: 200
      },
      {
        headerName: "时间",
        field: "DateTime",
        width: 200
      },
      {
        headerName: "分数",
        field: "CG_LT_GL_GL04_Score",
        width: 120
      },
      {
        headerName: "实际风速",
        field: "CG_LT_GL_GL04_FSSJ",
        width: 120
      },
      {
        headerName: "3#上部压差",
        field: "CG_LT_GL_GL04_SBYC03",
        width: 120
      },
      {
        headerName: "鼓风动能KG",
        field: "CG_LT_GL_GL04_GFDNKG",
        width: 140
      }, {
        headerName: "4#上部压差",
        field: "CG_LT_GL_GL04_SBYC04",
        width: 120
      }, {headerName: "富氧流量", field: "CG_LT_GL_GL04_FYLL", width: 140}, {
        headerName: "1#下部压差",
        field: "CG_LT_GL_GL04_XBYC01",
        width: 120
      }, {headerName: "进水温度", field: "CG_LT_GL_GL04_JSWD", width: 120}, {
        headerName: "2#下部压差",
        field: "CG_LT_GL_GL04_XBYC02",
        width: 120
      }, {headerName: "1#炉顶温度", field: "CG_LT_GL_GL04_LDWD01", width: 120}, {
        headerName: "3#下部压差",
        field: "CG_LT_GL_GL04_XBYC03",
        width: 120
      }, {headerName: "2#炉顶温度", field: "CG_LT_GL_GL04_LDWD02", width: 120}, {
        headerName: "4#下部压差",
        field: "CG_LT_GL_GL04_XBYC04",
        width: 120
      }, {headerName: "3#炉顶温度", field: "CG_LT_GL_GL04_LDWD03", width: 120}, {
        headerName: "透气性指数",
        field: "CG_LT_GL_GL04_TQXZS",
        width: 120
      }, {headerName: "4#炉顶温度", field: "CG_LT_GL_GL04_LDWD04", width: 120}, {
        headerName: "热负荷",
        field: "CG_LT_GL_GL04_RFH",
        width: 120
      }, {headerName: "阀座温度", field: "CG_LT_GL_GL04_FZWD", width: 120}, {
        headerName: "T阀座温度/T顶温",
        field: "CG_LT_GL_GL04_ZXQL",
        width: 120
      }, {headerName: "高炉软水总流量", field: "CG_LT_GL_GL04_GLRSZLL", width: 120}, {
        headerName: "上部压差占比",
        field: "CG_LT_GL_GL04_SBYCZB",
        width: 120
      }, {headerName: "冷风压力", field: "CG_LT_GL_GL04_LFYL", width: 120}, {
        headerName: "煤气在线分析",
        field: "CG_LT_GL_GL04_COZXFX",
        width: 120
      }, {headerName: "中部压差占比", field: "CG_LT_GL_GL04_ZBYCZB", width: 120}, {
        headerName: "冷风流量",
        field: "CG_LT_GL_GL04_LFLL",
        width: 120
      }, {headerName: "CO2在线分析", field: "CG_LT_GL_GL04_CO2ZXFX", width: 120}, {
        headerName: "下部压差占比",
        field: "CG_LT_GL_GL04_XBYCZB",
        width: 120
      }, {headerName: "热风压力02", field: "CG_LT_GL_GL04_RFYL02", width: 120}, {
        headerName: "N2在线分析",
        field: "CG_LT_GL_GL04_N2ZXZF",
        width: 120
      }, {headerName: "炉顶温度", field: "CG_LT_GL_GL04_DW", width: 120}, {
        headerName: "热风温度",
        field: "CG_LT_GL_GL04_RFWD",
        width: 120
      }, {headerName: "H2在线分析", field: "CG_LT_GL_GL04_H2ZXZF", width: 120}, {
        headerName: "下部压差",
        field: "CG_LT_GL_GL04_XBYC",
        width: 120
      }, {headerName: "炉顶压力", field: "CG_LT_GL_GL04_LDYL", width: 120}, {
        headerName: "1#上部压差",
        field: "CG_LT_GL_GL04_SBYC01",
        width: 120
      }, {headerName: "上部压差", field: "CG_LT_GL_GL04_SBYC", width: 120}, {
        headerName: "标准风速",
        field: "CG_LT_GL_GL04_FSBZ",
        width: 120
      }, {headerName: "2#上部压差", field: "CG_LT_GL_GL04_SBYC02", width: 120}, {
        headerName: "焦比",
        field: "CG_LT_GL_GL04_FCokeRate",
        width: 120
      },
      {
        headerName: "煤比", field: "CG_LT_GL_GL04_FCoalRate", width: 120
      },
      {
        headerName: "压差",
        field: "CG_LT_GL_GL04_YC",
        width: 120
      },
      {headerName: "煤气利用率", field: "CG_LT_GL_GL04_MQLYL", width: 120}
    ];

    const dateFormat = 'YYYY-MM-DD';
    return (


      <div style={{height: '100%'}}>
        <Card title="历史数据" bordered={false} style={{marginBottom: 10}}>
          <RangePicker
            format={dateFormat}
            placeholder={['开始时间', '结束时间']}
            onChange={this.timePick}
            key={Math.random()}
            defaultValue={[moment(startTime, dateFormat), moment(endTime, dateFormat)]}
          />

          <Button style={{float: 'right'}} type="default" shape="round" size='small'
                  onClick={this.downloadHistory}>下载</Button>
        </Card>


        {/* <Table */}
        {/*  columns={columns} */}
        {/*  dataSource={predictHistory} */}
        {/*  pagination={false} */}
        {/*  bordered */}
        {/*  scroll={{x: 'max-conent'}} */}
        {/* /> */}

        <div className="ag-theme-material" style={{height: 500, width: '100%', paddingBottom: 10}}>
          <AgGridReact
            columnDefs={columns}
            rowData={predictHistory}
            onGridReady={this.onGridReady}
            overlayLoadingTemplate={overlayLoadingTemplate}
            overlayNoRowsTemplate={overlayNoRowsTemplate}
            defaultColDef={this.state.defaultColDef}
            suppressRowTransform
          />
        </div>
      </div>

    )
  }
}

export default connect(({gaolu, loading}) => ({
  predictHistory: gaolu.predictHistory,
  fetchingHistoryNotice: loading.effects['gaolu/getHistory']
}))
(History);
